#!/usr/bin/env python
# coding=utf-8

# File Name: getURL.py
# Author: Bill Zhang
# Mail: zchcandid@gmail.com 
# Created Time: Fri 29 Nov 2013 04:10:49 PM CST
#mysql connector
import mysql.connector
from mysql.connector import errorcode
#import simplejson as json
import pika
#database name
Dbase="digikey"
def runUpdate(times,Dbase):
    db=MysqlConnect(Dbase)
    Mydb=db.cursor(buffered=True)
    Query="SELECT id,goods_url from ecs_goods LIMIT %s,500" % str(times*500)
    Mydb.execute(Query)
    #get url from ecs_goods
    for URL in Mydb: 
        if not URL:
            print("ALL price has been update")
            return 666 
        if not URL[0]:
            continue
        message='{"ID":%s,"URL":"%s"}' %(int(URL[0]),URL[1]) 
        pushURL(message=message)
        #print(URL)
    return 0

def pushURL(message):
    #push the messages to MQ
    parameters = pika.ConnectionParameters(host = 'localhost' )
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue = 'icmall' , durable = True )

    message =message
   # print("in libGetURL")
   # print(message)
    # make message persistent 
    channel.basic_publish(exchange = '', routing_key = 'icmall',body = message,properties=pika.BasicProperties(delivery_mode=2,))
   # print("The message has send")
    connection.close()
def MysqlConnect(DataBase):
    try:
          cnx = mysql.connector.connect(user='root', password='123456',host='192.168.100.201',database=DataBase)
         # cnx = mysql.connector.connect(user='admin001', password='admin001',host='192.168.100.58',database=DataBase)
    except mysql.connector.Error as err:
          if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
              print("Something is wrong with your user name or password")
          elif err.errno == errorcode.ER_BAD_DB_ERROR:
              print("Database does not exists")
          else:
              print(err)
    else:
        return cnx 
